﻿using Dapper_Core.BLL.Interface;
using Dapper_Core.DAL.Impl;
using Dapper_Core.Model;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Text;
using ExpressionToWhere;
using System.Linq;
using Newtonsoft.Json;
using Dapper_Core.Common;
using Audit.Core;
using System.Reflection;
using Dapper_Core.Table;

namespace Dapper_Core.BLL.Impl
{
    public class Sys_DictionaryBusiness : BaseRepository<Sys_Dictionary>, ISys_DictionaryBusiness
    {
        public Sys_DictionaryBusiness()
        {

        }

        public Sys_DictionaryBusiness(DBEntity dbEntity) : base(dbEntity)
        {

        }

        public Sys_DictionaryBusiness(TransactionContext transactionContext) : base(transactionContext)
        {

        }

        public bool IsExist(string dictCode)
        {
            try
            {
                if (string.IsNullOrEmpty(dictCode)) return true;
                Expression<Func<Sys_Dictionary, bool>> exp = dictionary => dictionary.DictCode == dictCode;
                List<Sys_Dictionary> list = base.GetList(exp, false).ToList();
                if (list != null && list.Count > 0) return true;
                return false;
            }
            catch (Exception ex)
            {
                NlogUtility.WriteError(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName, "检查系统字典是否存在失败", "dictCode=" + dictCode, ex, "DapperCore");
                return false;
            }
        }

        public bool Add(Sys_Dictionary dictionary)
        {
            using (AuditScope scope = AuditScope.Create("Sys_Dictionary:Add", () => dictionary))
            {
                try
                {
                    scope.Comment("添加单个系统字典项");
                    scope.SetCustomField("Module", "Sys_Dictionary");
                    scope.SetCustomField("Operator", SessionUtility.GetBasicUserInfo().PinyinCode);
                    scope.SetCustomField("Operation", Operation.Insert);
                    bool success = base.Add(dictionary);
                    if (!success)
                    {
                        scope.Discard();
                    }
                    return success;
                }
                catch (Exception ex)
                {
                    scope.Discard();
                    NlogUtility.WriteError(MethodBase.GetCurrentMethod().DeclaringType.FullName, "系统字典添加失败", "dictionary=" + JsonConvert.SerializeObject(dictionary), ex, "DapperCore");
                    return false;
                }
            }
        }

        public bool Update(Sys_Dictionary dictionary)
        {
            Sys_Dictionary old = base.Get(dictionary.DictCode);
            using (AuditScope scope = AuditScope.Create("Sys_Dictionary:Edit", () => old))
            {
                try
                {
                    scope.Comment("编辑单个系统字典项");
                    scope.SetCustomField("Module", "Sys_Dictionary");
                    scope.SetCustomField("Operator", SessionUtility.GetBasicUserInfo().PinyinCode);
                    scope.SetCustomField("Operation", Operation.Update);
                    old = dictionary;
                    bool success = base.Update(dictionary);
                    if (!success)
                    {
                        scope.Discard();
                    }
                    return success;
                }
                catch (Exception ex)
                {
                    scope.Discard();
                    NlogUtility.WriteError(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName, "系统字典项修改失败", "menu=" + JsonConvert.SerializeObject(dictionary), ex, "DapperCore");
                    return false;
                }
            }
        }

        public bool Delete(string ids, string deleter)
        {
            using (AuditScope scope = AuditScope.Create("Sys_Dictionary:Delete", () => ids))
            {
                try
                {
                    if (string.IsNullOrEmpty(ids)) return true;
                    List<string> idList = ids.Split(',', StringSplitOptions.RemoveEmptyEntries).ToList();
                    if (idList.Count < 1) return true;
                    scope.Comment("软删除系统字典项");
                    scope.SetCustomField("Module", "Sys_Dictionary");
                    scope.SetCustomField("Operator", deleter);
                    scope.SetCustomField("Operation", Operation.Delete);
                    //定义时间变量，保证同一次删除数据的删除时间相等
                    DateTime dateTime = DateTime.Now;
                    Expression<Func<Sys_Dictionary, bool>> exp = dictionary => dictionary.DictCode.In(idList);
                    bool success = base.SoftDelete(exp, deleter, dateTime);
                    if (!success)
                    {
                        scope.Discard();
                    }
                    return success;
                }
                catch (Exception ex)
                {
                    scope.Discard();
                    NlogUtility.WriteError(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName, "删除系统字典项失败", "ids=" + ids + "，deleter=" + deleter, ex, "DapperCore");
                    return false;
                }
            }
        }

        public List<Sys_Dictionary> GetList(Expression<Func<Sys_Dictionary, bool>> exp, bool addTopItem)
        {
            try
            {
                List<Sys_Dictionary> list = base.GetList(exp, false).ToList();
                if (addTopItem)
                {
                    list.Insert(0, new Sys_Dictionary() { DictCode = "", DictName = "--请选择--" });
                }
                return list;
            }
            catch (Exception ex)
            {
                NlogUtility.WriteError(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName, "获取字典项列表信息失败", $"exp={exp}，addTopItem={addTopItem}", ex, "DapperCore");
                List<Sys_Dictionary> list = new List<Sys_Dictionary>();
                if (addTopItem)
                {
                    list.Insert(0, new Sys_Dictionary() { DictCode = "", DictName = "--请选择--" });
                }
                return list;
            }
        }

        public List<Sys_DictionaryExtend> GetExtendList(string search)
        {
            try
            {
                Expression<Func<Sys_Dictionary, bool>> exp = dictionary => dictionary.IsDeleted == 0 && (dictionary.DictName.Contains(search) || dictionary.DictCode.Contains(search));
                NlogUtility.WriteInfo(MethodBase.GetCurrentMethod().DeclaringType.FullName, "查询字典信息", "search=" + search, "DapperCore");
                return SetVirtualParentCode(base.GetList(exp, false, "OrderNo asc").ToList());
            }
            catch (Exception ex)
            {
                NlogUtility.WriteError(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName, "获取字典项Ext列表信息失败", "search=" + search, ex, "DapperCore");
                return new List<Sys_DictionaryExtend>();
            }
        }

        private List<Sys_DictionaryExtend> SetVirtualParentCode(List<Sys_Dictionary> dictionarys)
        {
            List<Sys_DictionaryExtend> virtualMenus = new List<Sys_DictionaryExtend>();
            Sys_DictionaryExtend virtualDictionary = null;
            foreach (Sys_Dictionary item in dictionarys)
            {
                virtualDictionary = new Sys_DictionaryExtend();
                virtualDictionary.DictName = item.DictName;
                virtualDictionary.DictValue = item.DictValue;
                virtualDictionary.DictCode = item.DictCode;
                virtualDictionary.DictType = item.DictType;
                virtualDictionary.OrderNo = item.OrderNo;
                virtualDictionary.ParentCode = item.ParentCode;
                virtualDictionary.IsActive = item.IsActive;
                virtualDictionary.IsDeleted = item.IsDeleted;
                virtualDictionary.Creator = item.Creator;
                virtualDictionary.CreateDate = item.CreateDate;
                virtualDictionary.Modifier = item.Modifier;
                virtualDictionary.ModifyDate = item.ModifyDate;
                virtualDictionary.Deleter = item.Deleter;
                virtualDictionary.DeleteDate = item.DeleteDate;
                virtualDictionary.Remarks = item.Remarks;
                virtualDictionary.VirtualParentCode = GetVirtualParentCode(dictionarys, item);
                virtualMenus.Add(virtualDictionary);
            }
            return virtualMenus;
        }

        private string GetVirtualParentCode(List<Sys_Dictionary> dictionarys, Sys_Dictionary item)
        {
            if (item.ParentCode == "0") return item.ParentCode;
            if (dictionarys.Where(a => a.DictCode == item.ParentCode).Count() > 0) return item.ParentCode;
            return "0";
        }
    }
}
